﻿public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int val=0, ListNode next=null) 
    { 
        this.val = val;
        this.next = next;
    }
}
public class Solution {
    public ListNode SwapPairs(ListNode head)
    {
        // 无需交换
        if (head is null || head.next is null)
        {
            return head;
        }
        // 两两交换
        ListNode pre = head, cur = head.next, tmp;
        ListNode h = head.next;
        while (cur is not null)
        {
            tmp = cur.next;
            cur.next = pre;
            if (tmp is not null && tmp.next is not null)
            {
                pre.next = tmp.next;
            }
            else
            {
                pre.next = tmp;
            }
            
            pre = tmp;
            if (pre is not null)
            {
                cur = pre.next;
            }
            else
            {
                cur = pre;
            }
            
        }
        return h;
    }

    public static void Main(string[] args)
    {
        int[] head = [1, 2, 3, 4, 5];
        
        // 构建链表
        ListNode headNode = new ListNode(head[0]);
        ListNode pre = headNode;
        foreach (int h in head[1..])
        {
            ListNode l = new ListNode(h);
            pre.next = l;
            pre = pre.next;
        }
        
        // 两两交换
        Solution solution = new Solution();
        headNode = solution.SwapPairs(headNode);
        pre = headNode;
        while (pre is not null)
        {
            Console.Write($"{pre.val} ");
            pre = pre.next;
        }
    }
}